package com.ss.android.common.load;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

public final class MultiAsyncLoader<K, T, E, V, R> extends AbsAsyncLoader<K, T, E, V, R, Set<V>, MNode<K, T, E, V, R>> {
    public interface LoaderProxy<K, T, E, V, R> {
        R doInBackground(K key, T param, E extra);

        void onLoaded(K key, T param, Collection<V> collection, R result);
    }

    private final WeakReference<LoaderProxy<K, T, E, V, R>> mProxyRef;
    private final Collection mTmpColl;

    public MultiAsyncLoader(int capacity, int maxWorker, LoaderProxy loaderProxy) {
        super(capacity, maxWorker);
        loaderProxy.getClass().getName();
        this.mProxyRef = new WeakReference(loaderProxy);
        this.mTmpColl = new ArrayList();
    }

    protected final MNode<K, T, E, V, R> makeNode() {
        return new MNode<>();
    }

    protected final R doInBackground(K key, T param, E extra) {
        LoaderProxy<K, T, E, V, R> loaderProxy = this.mProxyRef.get();
        return loaderProxy != null ? loaderProxy.doInBackground(key, param, extra) : null;
    }

    protected final void onLoaded(K key, T param, E extra, Set<V> obj, R result) {
        LoaderProxy<K, T, E, V, R> loaderProxy = this.mProxyRef.get();
        if (loaderProxy != null) {
            this.mTmpColl.clear();
            Iterator<V> iterator = obj.iterator();
            while (iterator.hasNext()) {
                V v = iterator.next();
                if (v != null) {
                    this.mTmpColl.add(v);
                }
            }

            loaderProxy.onLoaded(key, param, this.mTmpColl, result);
            this.mTmpColl.clear();
        }
    }

    public final void stop() {
        super.stop();
        this.mProxyRef.clear();
    }
}

